<template>
  <div class="coupon-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item>
          <UserSelect
            v-model="queryParams.userId"
            placeholder="选择用户"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-select
            style="width: 192px"
            v-model="queryParams.status"
            placeholder="红包状态"
            clearable
          >
            <el-option label="未使用" value="未使用" />
            <el-option label="已使用" value="已使用" />
            <el-option label="已过期" value="已过期" />
            <el-option label="已作废" value="已作废" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <div class="top-actions">
        <el-button type="primary" @click="handleAdd">新增红包</el-button>
      </div>

      <el-table
        :data="couponList"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="userId" label="用户信息">
          <template #default="scope">
            <div v-if="userMap[scope.row.userId]">
              {{
                userMap[scope.row.userId].name ||
                userMap[scope.row.userId].username ||
                "未知用户"
              }}
              <div class="user-id-info">ID: {{ scope.row.userId }}</div>
            </div>
            <div v-else>ID: {{ scope.row.userId }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="红包金额">
          <template #default="scope"> {{ scope.row.amount }} 元 </template>
        </el-table-column>
        <el-table-column label="有效期" width="300">
          <template #default="scope">
            {{ formatDate(scope.row.validFrom) }} 至
            {{ formatDate(scope.row.validTo) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getCouponStatusTag(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="useTime" label="使用时间">
          <template #default="scope">
            {{ scope.row.useTime ? formatDate(scope.row.useTime) : "-" }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === '未使用'"
              size="small"
              type="primary"
              @click="handleUse(scope.row)"
            >
              使用
            </el-button>
            <el-button
              v-if="scope.row.status === '未使用'"
              size="small"
              type="warning"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="scope.row.status === '未使用'"
              type="danger"
              size="small"
              @click="handleCancel(scope.row)"
            >
              作废
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加红包对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="couponFormRef"
        :model="couponForm"
        :rules="couponRules"
        label-width="100px"
      >
        <el-form-item label="用户" prop="userId">
          <UserSelect v-model="couponForm.userId" placeholder="请选择用户" />
        </el-form-item>
        <el-form-item label="红包金额" prop="amount">
          <el-input-number
            v-model="couponForm.amount"
            :min="0.01"
            :precision="2"
            :step="1"
            style="width: 100%"
            placeholder="请输入红包金额"
          />
        </el-form-item>
        <el-form-item label="有效期类型" prop="validityType">
          <el-radio-group v-model="couponForm.validityType">
            <el-radio :label="1">固定日期</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="couponForm.validityType === 1"
          label="有效期"
          prop="validDateRange"
        >
          <el-date-picker
            v-model="couponForm.validDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";
import UserSelect from "@/components/UserSelect.vue";

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userId: "",
  status: "",
});

const loading = ref(false);
const total = ref(0);
const couponList = ref([]);

// 红包表单
const dialogVisible = ref(false);
const dialogTitle = ref("新增红包");
const couponFormRef = ref();
const couponForm = reactive({
  id: null,
  userId: null,
  amount: 10,
  validityType: 1,
  validDateRange: [],
});

// 红包表单校验规则
const couponRules = {
  userId: [{ required: true, message: "请选择用户", trigger: "blur" }],
  amount: [{ required: true, message: "请输入红包金额", trigger: "blur" }],
  validityType: [
    { required: true, message: "请选择有效期类型", trigger: "change" },
  ],
  validDateRange: [
    {
      required: true,
      message: "请选择有效期范围",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (!value || value.length !== 2) {
          callback(new Error("请选择有效期范围"));
        } else {
          callback();
        }
      },
    },
  ],
};

// 获取红包状态标签样式
const getCouponStatusTag = (status) => {
  switch (status) {
    case "未使用":
      return "success";
    case "已使用":
      return "info";
    case "已过期":
      return "warning";
    case "已作废":
      return "danger";
    default:
      return "info";
  }
};

// 格式化日期，只显示年月日
const formatDate = (dateString) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleDateString(); // 只显示日期部分，不显示时间
};

// 用户信息缓存
const userMap = reactive({});

// 获取所有用户列表
const getAllUsers = async () => {
  try {
    const response = await request({
      url: "/user/all", // 使用新添加的接口
      method: "get",
    });

    if (response.data && Array.isArray(response.data)) {
      response.data.forEach((user) => {
        userMap[user.id] = user;
      });
    }
  } catch (error) {
    console.error("获取所有用户列表出错，尝试使用分页接口:", error);
    // 如果/user/all接口不存在，尝试使用分页接口获取更多用户
    try {
      const pageResponse = await request({
        url: "/user/list",
        method: "get",
        params: {
          pageNum: 1,
          pageSize: 1000,
        },
      });

      if (pageResponse.data && pageResponse.data.list) {
        pageResponse.data.list.forEach((user) => {
          userMap[user.id] = user;
        });
      }
    } catch (pageError) {
      console.error("获取用户列表分页数据出错:", pageError);
    }
  }
};

// 查询红包列表
const getCouponList = async () => {
  loading.value = true;
  try {
    const { userId, status, pageNum, pageSize } = queryParams;
    let params = { pageNum, pageSize };

    if (userId) params.userId = userId;
    if (status) params.status = status;

    const response = await request({
      url: "/coupon/list",
      method: "get",
      params,
    });
    couponList.value = response.data.list;
    total.value = response.data.total;

    // 获取用户信息
    const userIds = couponList.value.map((item) => item.userId);
    getAllUsers();
  } catch (error) {
    console.error("查询红包列表出错:", error);
    ElMessage.error("查询红包列表出错");
  } finally {
    loading.value = false;
  }
};

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1;
  getCouponList();
};

// 重置按钮
const resetQuery = () => {
  queryParams.userId = "";
  queryParams.status = "";
  handleQuery();
};

// 新增红包
const handleAdd = () => {
  resetCouponForm();
  dialogTitle.value = "新增红包";
  dialogVisible.value = true;
};

// 使用红包
const handleUse = (row) => {
  ElMessageBox.confirm(`确认使用ID为${row.id}的红包吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const response = await request({
          url: `/coupon/${row.id}/use`,
          method: "post",
        });
        ElMessage.success("使用成功");
        getCouponList();
      } catch (error) {
        console.error("使用红包出错:", error);
        // ElMessage.error("使用红包出错");
      }
    })
    .catch(() => {});
};

// 取消红包（作废）
const handleCancel = (row) => {
  ElMessageBox.confirm(`确认作废ID为${row.id}的红包吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const response = await request({
          url: `/coupon/${row.id}/cancel`,
          method: "post",
        });
        ElMessage.success("作废成功");
        getCouponList();
      } catch (error) {
        console.error("作废红包出错:", error);
        ElMessage.error("作废红包出错");
      }
    })
    .catch(() => {});
};

// 重置红包表单
const resetCouponForm = () => {
  couponForm.id = null;
  couponForm.userId = null;
  couponForm.amount = 10;
  couponForm.validityType = 1;
  couponForm.validDateRange = [];
};

// 编辑红包
const handleEdit = (row) => {
  resetCouponForm();
  dialogTitle.value = "编辑红包";

  // 设置表单值
  couponForm.userId = row.userId;
  couponForm.amount = parseFloat(row.amount);

  // 设置有效期，处理日期格式
  if (row.validFrom && row.validTo) {
    console.log("原始有效期:", row.validFrom, row.validTo);

    // 提取日期部分 (yyyy-MM-dd)
    const validFromDate = row.validFrom.substring(0, 10);
    const validToDate = row.validTo.substring(0, 10);

    // 设置日期范围数组
    couponForm.validDateRange = [validFromDate, validToDate];
    console.log("设置的日期范围:", couponForm.validDateRange);

    couponForm.validityType = 1;
  } else {
    console.error("编辑红包时，有效期数据不完整:", row);
  }

  // 保存编辑的红包ID
  couponForm.id = row.id;

  dialogVisible.value = true;
};

// 提交红包表单
const submitForm = () => {
  couponFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 单个创建或编辑
        const data = {
          userId: couponForm.userId,
          amount: couponForm.amount,
          status: "未使用",
        };

        // 如果是编辑模式，添加ID
        if (couponForm.id) {
          data.id = couponForm.id;
        }

        // 设置有效期 - 直接使用日期选择器的值，添加时间部分
        if (
          couponForm.validDateRange &&
          couponForm.validDateRange.length === 2
        ) {
          // 开始日期设为当天的00:00:00
          data.validFrom = `${couponForm.validDateRange[0]} 00:00:00`;
          console.log("前端设置的开始时间:", data.validFrom);

          // 结束日期设为当天的23:59:59
          data.validTo = `${couponForm.validDateRange[1]} 23:59:59`;
          console.log("前端设置的结束时间:", data.validTo);
        } else {
          console.error("有效期范围无效");
          ElMessage.error("请选择有效的日期范围");
          return;
        }

        let url, method;

        // 根据是否有ID决定是创建还是更新
        if (couponForm.id) {
          // 更新红包 - 使用update接口而非直接PUT
          url = `/coupon/update`;
          method = "post";
          // 确保ID包含在数据中
          data.id = couponForm.id;
        } else {
          // 创建新红包
          url = "/coupon/create";
          method = "post";
        }

        console.log("提交数据:", JSON.stringify(data));

        const response = await request({
          url,
          method,
          data,
        });

        ElMessage.success(couponForm.id ? "更新成功" : "创建成功");
        dialogVisible.value = false;
        getCouponList();
      } catch (error) {
        console.error(couponForm.id ? "更新红包出错:" : "创建红包出错:", error);
        ElMessage.error(couponForm.id ? "更新红包出错" : "创建红包出错");
      }
    }
  });
};

// 分页
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getCouponList();
};

const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getCouponList();
};

// 初始化
onMounted(() => {
  getCouponList();
  getAllUsers(); // 加载所有用户
});
</script>

<style lang="scss" scoped>
.coupon-container {
  padding: 10px;

  .filter-container {
    margin-bottom: 20px;
  }

  .table-container {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .top-actions {
      margin-bottom: 20px;

      .el-button {
        margin-right: 10px;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }

  .user-id-info {
    font-size: 12px;
    color: #909399;
  }
}
</style>
